<?php
/**
 * Author: xuxinlong
 * Date: 2017年08月06日
 */

namespace app\admin\controller;


use think\Controller;


class Login extends Controller
{
    public function index()
    {
        $Key = "phpsafe";
        //开启Session
        session_start();
        //如果Session中没有登录信息，尝试从Cookie中加载用户信息
        if (empty($_SESSION['UserInfo']['id'])) {
            if (!empty($_COOKIE['Login'])) {
                $Value = $_COOKIE['Login'];
                // 去掉魔术引号
                if (get_magic_quotes_gpc()) {
                    $Value = stripslashes($Value);
                }
                $Str = substr($Value, 0, 32);
                $Value = substr($Value, 32);
                //校验
                if (md5($Value . $Key) == $Str) {
                    $User = unserialize($Value);

                    $_SESSION['UserInfo'] = $User;

                } else {
                    $this->redirect('login');
                }
            } else {
                $this->redirect('login');
            }
        }
        return $this->fetch();
    }

    /**
     * 登录页面
     * @return mixed
     */
    public function login()
    {
        return $this->fetch();
    }

    /**
     * 检验登录
     */
    public function doLogin()
    {
        $Key = "phpsafe";
        session_start();
        if ($_POST['username'] == 'admin' && $_POST['password'] == '888888') {
            //登录成功
            $User['id'] = 1;        //用户id
            $User['name'] = 'phpsafe.com';    //用户显示名称
            $_SESSION['UserInfo'] = $User;

            //如果选中记住我，就将登录信息放入Cookie中
            if ($_POST['check'] == '1') {
                //将登录信息，存放在Cookie中
                $Value = serialize($User);
                $Str = md5($Value . $Key);
                setcookie('Login', $Str . $Value, time() + 60 * 60 * 24 * 30, '/');
            }
            $this->redirect('index');
        } else {
            echo '用户名或密码不匹配';
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        setcookie('Login', '', time() - 1, '/');
        session_unset();
        session_destroy();
        $this->redirect('login');
    }

}